package com.wangsong.websocket;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;



import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/websocket")
public class WebSocket {
	public static ArrayList<Map<String, Object>> mapList=new ArrayList<>();
	
    @OnOpen
    public void onOpen(Session session) {
    
    	Map<String, Object> map=new HashMap<>();
        map.put("session", session);
        mapList.add(map);
    }

    @OnClose
    public void onClose(Session session) {
    	for(int i=0;i<mapList.size();i++){
    		Map<String, Object> map=mapList.get(i);
    		if(map.get("session")==session){
    			mapList.remove(i);
    			break;
    		}
    	}
    }
    
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
		for(int i=0;i<mapList.size();i++){
    		Map<String, Object> map=mapList.get(i);
    		if(map.get("session")==session){
    			map.put("id", message);
    			mapList.remove(i);
    			mapList.add(map);
    			break;
    		}
    	}
    }

    @OnError
    public void onError(Session session, Throwable error) {
        
    }
    public static void send(String id,String msg) throws IOException  {
	  	for(int i=0;i<mapList.size();i++){
			Map<String, Object> map=mapList.get(i);
			if(map.get("id").equals(id)){
				Session session =(Session) map.get("session");
				session.getBasicRemote().sendText(msg);
				break;
			}
		}
    }
}
